<?php
/*
 * 文章管理
 */
namespace Admin\Controller;
use QL\QueryList;

use Admin\Model\articleModel;
use Admin\Model\articletypeModel;
use Admin\Model\goodsModel;
use Admin\Model\memberModel;
use Admin\Model\guestbookModel;


class articleController extends BaseController {
    
    public $articleModel;
    public $articletypeModel;
    public function __construct() {
        parent::__construct();
        $this->articleModel = new articleModel();
        $this->articletypeModel = new articletypeModel();
        $this->_get_atype();//获取文章分类
    }
    
    protected function _get_article_where(){
        $arrow = array(
            "title","status","is_check"
        );//允许提交的数据
        $data = param_filter($_GET,$arrow,$must=NULL,$filter=true);//过滤数据
        
        $where = "1";
        //todo
        if(is_set($data,'title')){
            $where .= " AND title like '%".$data['title']."%'";
        }
        
        return $where;
    }
    
    /*
     * 统计文章数量
     */
    protected function _get_article_count(){
        
        $where = $this->_get_article_where();//不带status的查询条件
        //全部文章
        //0全部,1正常,2待审核,3删除
//is_check 1审核通过 2待审核 3审核不通过
//status 1正常 0.删除
        
        $article_count =  array();
        
        $article_count[1] = $this->articleModel->getArticleCount($where." AND status=1 AND is_check=1");//正常
        $article_count[2] = $this->articleModel->getArticleCount($where." AND status=1 AND is_check=2 ");//待审核
        $article_count[3] = $this->articleModel->getArticleCount($where." AND status=1 AND is_check=3 ");//审核不通过
        $article_count[4] = $this->articleModel->getArticleCount($where." AND status=0");//已删除

        return $article_count;
    }
    
    
    /*
     * 正常的文章列表
     */
    public function index(){
        
        $page = get('p',1);
        $where = $this->_get_article_where();
        $where .= " AND status = 1 AND is_check=1";
        
        //统计数量
        $article_count = $this->_get_article_count();
        $this->assign('article_count',$article_count);

        $article_list = $this->articleModel->getArticleList($where,$page);

		$page_size = C('PAGE_SIZE');
		$count = $this->articleModel->getArticleCount($where);//全部
        $page = new \Think\Page($count, $page_size);
        $show = $page->show3();
        $this->assign('page', $show);
		
		
        $this->assign('datalist',$article_list);
        $this->display();
        
    }
    
    /*
     * 已经删除的文章列表
     */
    public function dellist(){
    
        $page = get('p',1);
        $where = $this->_get_article_where();
        $where .= " AND status = 0";
    
        //统计数量
        $article_count = $this->_get_article_count();
        $this->assign('article_count',$article_count);
    
        $article_list = $this->articleModel->getArticleList($where,$page);
		
		$page_size = C('PAGE_SIZE');
		$count = $this->articleModel->getArticleCount($where);//全部
        $page = new \Think\Page($count, $page_size);
        $show = $page->show3();
        $this->assign('page', $show);
		
        $this->assign('datalist',$article_list);
        $this->display('index');
    
    }
    
    
    /*
     * 删除ajax
     */
    public function del(){
    
        $id = get("id");
        $status = get("status");
        $where = array(
            "article_id" => $id
        );
    
        if(!$id){
            return_json(1,"当前文章不可删除");
        }
        
        $data = array(
            "status" => $status
        );
    
        $res = $this->articleModel->editArticle($where, $data);
        if($res){
            return_json(0,"操作成功");
        }
        return_json(1,"操作失败");
    
    }
    
    /*
     * 审核ajax
     */
    public function shenhe(){
    
        $id = get("id");
        $status = get("status");
        
        $where = array(
            "article_id" => $id
        );
    
        if(!$id){
            return_json(1,"当前文章不可操作");
        }
    
        $data = array(
            "is_check" => $status
        );
    
        $res = $this->articleModel->editArticle($where, $data);
        if($res){
            return_json(0,"操作成功");
        }
        return_json(1,"操作失败");
    
    }


    
    /*
     * 待审核的的文章
     */
    public function waitpass(){
        
        $page = get('p',1);
        $where = $this->_get_article_where();
        $where .= " AND status = 1 AND is_check=2";

        //统计数量
        $article_count = $this->_get_article_count();
        $this->assign('article_count',$article_count);
        
        $article_list = $this->articleModel->getArticleList($where,$page);
		
		$page_size = C('PAGE_SIZE');
		$count = $this->articleModel->getArticleCount($where);//全部
        $page = new \Think\Page($count, $page_size);
        $show = $page->show3();
        $this->assign('page', $show);
		
		
        $this->assign('datalist',$article_list);
        $this->display('index');
    }
    
    /*
     * 审核不通过的文章
     */
    public function nopass(){
        $page = get('p',1);
        $where = $this->_get_article_where();
        $where .= " AND status = 1 AND is_check=3";

        //统计数量
        $article_count = $this->_get_article_count();
        $this->assign('article_count',$article_count);
        
        $article_list = $this->articleModel->getArticleList($where,$page);
		
		$page_size = C('PAGE_SIZE');
		$count = $this->articleModel->getArticleCount($where);//全部
        $page = new \Think\Page($count, $page_size);
        $show = $page->show3();
        $this->assign('page', $show);
		
		
        $this->assign('datalist',$article_list);
        $this->display('index');
    }
    
    /*
     * 添加文章图片
     */
    public function uploadpic(){
        
        if(empty($_FILES)){
            return_json(1,"请上传图片");
        }
        
        $res = $this->iupload("article");//上传操作
        //上传失败
        if(empty($res)){
            return_json(1,"上传失败,请重新上传");
        }
        
        return_json(0,"上传完毕",$res);
    }
    
    /*
     *添加文章
*/
    
    public function addarticle(){
        if(!IS_AJAX){
            return_json(1,"系统错误");
        }
        
        $article_id = get("article_id");
       
        $arrow = array(
            "atype_id","author_uid","title","author",
            "author_duty","author_desc","is_original",
            "original","keywords",
            "description","allowcomment","article_thumb",
            "is_thumb","thumb_from","start_nums","praise_start","more_url","need_guestbook","book_tips",
            "content","try_content","is_free","goods_id","buy_btn","is_zanshang","zanshang_type","zanshang_desc",
            "zanshang_btn1","zanshang_btn2","zanshang_money","zanshang_static","ord","is_title"
        );
        $must = array(
            "title"
        );
        
        $article_data = param_filter($_POST,$arrow,$must,true,true);
        
        if(empty($article_data)){
            return_json(1,"请检查填写的内容");
        }
        
        //作者id
        if($article_data['author_uid']){
            
            $memberModel = new memberModel();
            $authorinfo = $memberModel->getMember(array("uid"=>$article_data['author_uid']));
            
            if(empty($authorinfo)){
                return_json(1,"请检查讲师信息ID");
            }
            $article_data['author'] = $article_data['author'] ? $article_data['author'] : ($authorinfo['realname'] ? $authorinfo['realname'] : $authorinfo['nickname']);
            $article_data['author_duty'] = $article_data['author_duty'] ? $article_data['author_duty'] : $authorinfo['duty'];
            $article_data['author_desc'] = $article_data['author_desc'] ? $article_data['author_desc'] : $authorinfo['note'];
            $article_data['author_headimgurl'] = $authorinfo['headimgurl'] ? $authorinfo['headimgurl'] : $article_data['headimgurl'];
            
            if(empty($article_data['author'])){
                return_json(1,"请检查讲师名字");
            }
            
            if(empty($article_data['author_duty'])){
                return_json(1,"请检查讲师职位称呼");
            }
            
            if(empty($article_data['author_desc'])){
                return_json(1,"请填写讲师介绍");
            }
            
        }
        
        
        $article_thumb = $_POST["article_thumb"];
       
        if(empty($article_thumb)){
            return_json(1,"请上传文章图片");
        }
        
        $article_data['thumb'] = current($article_thumb);//文章主图
        $article_data['article_thumb'] = json_encode($article_thumb);//把数组拼接成字符串
        
        
        //打赏设置
        if($article_data['is_zanshang'] == 1){

            if(!in_array($article_data['zanshang_type'],array(3,5))){
                return_json(1,"请设置支付/赞赏类型");
            }
            //支付按钮
            if(empty($article_data['zanshang_btn1']) || empty($article_data['zanshang_btn1']) || empty($article_data['zanshang_desc'])){
                
                if($article_data['zanshang_type'] == 3){
                    return_json(1,"请设置赞赏按钮和赞赏提示");
                }else{
                    return_json(1,"请设置支付按钮和支付提示");
                }
                
            }
            
            //打赏金额
            if($article_data['zanshang_type'] == 3){
                
                //打赏
                if(!$article_data['zanshang_money']){
                    return_json(1,"请设置打赏金额");
                }else if($article_data['zanshang_money']>200){
                    return_json(1,"打赏金额不能超过200元");
                }

            }else{
                
                //支付
                if(!$article_data['zanshang_money']){
                    return_json(1,"请设置支付金额");
                }else if($article_data['zanshang_money']>50000){
                    return_json(1,"支付金额不能超过5万");
                }
            }
        }
        
        
        //留言板
        if($article_data['need_guestbook']){
            if(!$article_data['book_tips']){
                return_json(1,"请设置留言提示文字");
            }
        }
        
        //商品
        if($article_data['goods_id']){
            
            $goodsModel = new goodsModel();
            $where_g = array(
                "goods_id" => $article_data['goods_id'],
                "ischeck" => 1,
                "stock" => array(
                    "gt",0
                )
            );
            $goods = $goodsModel->getGoods($where_g);
            
            if(empty($goods)){
                return_json(1,"请检查绑定的商品是否可以购买");
            }
        }
        
        
        //检查阅读原文链接
        if($article_data['more_url']){
            if(!check_url($article_data['more_url'])){
                return_json(1,"请检查阅读原文链接格式是否正确");
            }
        }
        
        
        $article_id = get("article_id");
        if($article_id){
            //编辑
            $article_data['update_time'] = date("Y-m-d H:i:s");//
            

            $where = array(
                "article_id" => $article_id
            );
            $res = $this->articleModel->editarticle($where,$article_data);
            if($res !== false){
                return_json(0,"编辑文章信息成功","","/admin/article/editdetail/?article_id=".$article_id);
            }
        }else{
            //新增
            $article_data['create_time'] = date("Y-m-d H:i:s");//创建时间
            $article_data['post_time'] = date("Y-m-d H:i:s");//创建时间
            
            //添加文章信息到数据库
            $article_id = $this->articleModel->addarticle($article_data);
            if($article_id){
                return_json(0,"添加文章信息成功","","/admin/article/editdetail/?article_id=".$article_id);
            }
        }
        
        return_json(1,"添加文章失败");
        
    }
    
    
    /*
     * 获取文章分类
     */
    public function _get_atype(){
        $data = $this->articletypeModel->getarticletypeList();
        $atypes = array();
        foreach($data as $k=>$v){
            $atypes[$v['atype_id']] = $v;
        }
        $this->assign('atype',$atypes);
        return $atypes;
    }
    
    
    /*
     * 添加文章
     */
    public function add(){
        $this->display('edit');
    }
    
    /*
     * 编辑文章
     */
    public function edit(){
        $article_id = get("article_id");
        $where  = array(
            "article_id" => $article_id
        );
        $article = $this->articleModel->getarticle($where);
        if(empty($article_id)){
            $this->error("该文章不存在","/admin/article/index");exit;
        }
        
        $this->assign("article",$article);
        $this->display();
    }
    
    
    /*
     * 编辑详情
     */
     public function editdetail(){
        
        $article_id = get("article_id");
        $where  = array(
            "article_id" => $article_id
        );
        
        if(IS_AJAX){

            $allow = array("description","keywords","content","try_content");
            $must = array("description","content");
            $data = param_filter($_POST, $allow,$must,false,true);//TODO
            if(empty($article_id)){
                return_json(1,"文章参数错误");
            }
            if(empty($data)){
                return_json(1,"文章详情和文章描述不能为空");
            }

            
            
            $content = htmlspecialchars_decode(stripslashes($data['content']));
            
            
            
            
            
        //采集规则
        $rules = array(

            //采集文章正文内容,利用过滤功能去掉文章中的超链接，但保留超链接的文字，并去掉版权、JS代码等无用信息
            'content' => array('','html','',function($content){
            //利用回调函数下载文章中的图片并替换图片路径为本地路径
            //使用本例请确保当前目录下有image文件夹，并有写入权限
            //由于QueryList是基于phpQuery的，所以可以随时随地使用phpQuery，当然在这里也可以使用正则或者其它方式达到同样的目的
            $doc = \phpQuery::newDocumentHTML($content);
            $imgs = pq($doc)->find('img');
            $thumb = '';
            $article_thumb = array();

            
            foreach ($imgs as $k=>$img) {

                $src = pq($img)->attr('data-src');
                
                $new_pic_url = save_remote($src,0);//下载远程图片 并上传到云存储
                
        	    if($new_pic_url){
        	        
        	        if($k==0){
        	            $thumb = $new_pic_url;
        	        }
        	        $article_thumb[] = $new_pic_url;
        	        
        	        $full_url = C("UPYUN_DOMAIN").$new_pic_url;
        	        
        	        pq($img)->attr('data-src',$full_url);//替换图片网址
        	        
        	        pq($img)->attr('src',$full_url);//替换图片网址
        	        
        	    }
            }
            
            //循环查找视频
            $iframes = pq($doc)->find('iframe');
            foreach ($iframes as $key=>$iframe) {
                $iframe_txt = pq($iframe)->htmlOuter();
                $videoid = getVideoId($iframe_txt);
                if(!$videoid){
                    continue;
                }
                $video_url = 'http://v.qq.com/iframe/player.html?vid='.$videoid.'&tiny=0&auto=0';
                $new_iframe = '<iframe class="edui-faked-video" src="'.$video_url.'" width="100%" style="max-width:640px;width:100%;" frameborder="no" border="0" allowfullscreen="true"></iframe>';
                pq($iframe)->replaceWith($new_iframe);
            
            }
            
            $data = array(
                "content" => $doc->htmlOuter()
            );
            
            return $data;
            })
        );
           
         
            //开始采集
            $content_data = QueryList::Query($content,$rules,'',null,null,true)->data;

            $data['content'] = htmlspecialchars(addslashes($content_data[0]['content']['content']));
            
            $res = $this->articleModel->editarticle($where, $data);
            if($res !== false){
                return_json(0,"编辑文章详情成功");
            }
            return_json(1,"编辑文章出错");
        }
        

        $article = $this->articleModel->getarticle($where);
        $article['content'] = htmlspecialchars_decode(stripslashes($article['content']));
        if(empty($article_id)){
            $this->error("该文章不存在","/admin/article/index");exit;
        }
        
        $this->assign("article",$article);

        $this->display();
    }
    
    /*
     * 文章分类
     */
    public function fenlei(){
        //$fenlei = $this->_get_atype();
        $this->display();
    }
    
    /*
     * 编辑分类
     */
    public function edittype(){
       
        $gid = get("atype_id");
        $where = array("atype_id"=>$gid);
        
        if(IS_POST){
            
            $atype_name = get("atype_name");
            
            if(!$atype_name){
                return_json(1,"请填写分类名称");
            }
            
            $data = array(
                "atype_name" => $atype_name,
                "atype_ord" => get("atype_ord")
            );

            $pic = $this->iupload("articletype");
            if($pic){
                $data['atype_icon'] = $pic['pic']['savepath'].$pic['pic']['savename'];
            }
            
            if($gid){
               $res = $this->articletypeModel->editArticletype($where, $data);
               if($res !== false){
                $this->redirect('/admin/article/fenlei');
               }
            }else{
               $res = $this->articletypeModel->add($data);
               if($res){
                $this->redirect('/admin/article/fenlei');
               }
            }
            
            return_json(1,"修改失败");
            
        }

        $res = $this->articletypeModel->getArticletype($where);

        $this->assign("data",$res);
       
        $this->display();
    }
    
    public function deltype(){
        $id = get("id");
        if($id){
            $res = $this->articletypeModel->where(array("atype_id"=>$id))->delete();
            if($res){
                return_json(0,"删除成功","","/admin/article/fenlei");
            }
        }
        return_json(1,"删除失败");
    }
    
    
    protected function _getfriend($uid){
    
        if(!$uid){
            return_json(1,"请检查讲师编号");
        }
    
        //判断是不是手机号码
        $is_mobile = check_mobile($uid);
        if($is_mobile){
            $where = array(
                "mobile" => $uid,
            );
        }else{
            $where = array(
                "uid" => $uid,
            );
        }
        $memberModel = new memberModel();
        $res = $memberModel->getMember($where);

        if(empty($res)){
            return_json(1,"未找到讲师信息,请检查");
        }
    
        return $res;
    
    }
    
    /*
     * 根据uid获取用户信息
     */
    public function getfriend(){
    
        $uid = get('uid');
        $res = $this->_getfriend($uid);
    
        return_json(0,"",$res);
    
    }
    
    /*
     * 报名留言
     */
    public function guestbook(){
        
        $page = get("p",1);
        $guestbookModel = new guestbookModel();
        $where = array();
        $res = $guestbookModel->getGuestbookList($where,$page);
        
        $pagecount = $guestbookModel->getGuestbookCount($where);
        
        $page = new \Think\Page($pagecount, C('PAGE_SIZE'));
        $show = $page->show3();
        $this->assign('page', $show);
        
        $this->assign("guestbook",$res);
        $this->display();
        
    }

    public function swiper () {
        $focusModel = M('focus');
        $where = array(
            "position" => 2,
        );
        $res = $focusModel->where($where)->select();
        $this->assign('datalist',$res);
        $this->display();
    }
    
    /*
     * 首页幻灯片设置
     */
    public function huandengpian(){
        $focusModel = M('focus');
        $id = get("focus_id");
        $where = array(
            "focus_id" => $id
        );
        if(!$id){
            return_json(1,"参数错误");
        }
        
        if(IS_POST){
            $data = param_filter($_POST,array("title","link","ord","status"),array("title","link","ord","status"));
            $pic = $this->iupload("slide");
            if($pic){
                $data['pic'] = $pic['pic']['savepath'].$pic['pic']['savename'];
            }
            
            if(!empty($data)){
                if($id){
                    $res = $focusModel->where($where)->save($data);
                }else{
                    $res = $focusModel->add($data);
                }
                if($res){
                    $this->redirect('/admin/article/swiper/');
                }
            }
        }
        
        $res = $focusModel->where($where)->find();
        
        if($res){
            $this->assign('focus',$res);
        }else{
            $this->error("不存在");
        }
        
        $this->display();

    }
    
    
}